import Component from "@glimmer/component";
import { ajax } from "discourse/lib/ajax";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class TopContributors extends Component {
  @tracked topContributors = null;
  order = this.args.params?.order || "likes_received";
  period = this.args.params?.period || "monthly";
  count = this.args.params?.count || 5;
  excludedGroupNames = this.args.params?.excludedGroupNames || "";

  constructor() {
    super(...arguments);

    ajax(this.requestURL).then((data) => {
      this.topContributors = data.directory_items?.slice(0, this.count);
      // 按照 order中的字段排序
      this.topContributors.sort((a, b) => b[`${this.order}`] - a[`${this.order}`]);
      // 因为用户名涉及隐私，如果大于5个字符，只显示前5个字符，后面用...代替
      this.topContributors.forEach((contributor) => {
        if (contributor.user.username.length > 5) {
          contributor.user.username = contributor.user.username.slice(0, 5) + "..";
        }
      });
    });
  }

  get requestURL() {
    return `/directory_items.json?period=${this.period}&order=${this.order}&exclude_groups=${this.excludedGroupNames}&limit=${this.count}`;
  }

  get viewAllUrl() {
    return `/u?order=${this.order}&period=${this.period}&exclude_groups=${this.excludedGroupNames}`;
  }

  willDestroy() {
    this.topContributors = null;
  }

  incremented(index) {
    return index + 1;
  }
}
